/*
 * MIT License
 *
 * Copyright (c) 2024 org.zzz (https://gitee.com/frostforest)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package org.zzz.pcdc;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PcdcResultSetHandler {
    /**
     * 将 ResultSet 中的当前行转换为 Map（字段名 -> 字段值）
     *
     * @param rs 结果集（需确保已调用 next() 定位到有效行）
     * @return 包含当前行数据的 Map
     * @throws SQLException 数据库操作异常
     */
    private static Map<String, Object> getRow(ResultSet rs) throws SQLException {
        Map<String, Object> rowMap = new HashMap<>();
        // 获取结果集元数据（包含字段信息）
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 遍历所有字段，添加到 Map
        for (int i = 1; i <= columnCount; i++) {
            // 字段名（使用数据库原始列名）
            String columnName = metaData.getColumnName(i);
            // 字段值（自动适配字段类型）
            Object value = rs.getObject(i);
            rowMap.put(columnName, value);
        }
        return rowMap;
    }

    /**
     * 将整个 ResultSet 转换为 List<Map>（包含所有行数据）
     *
     * @param rs 结果集
     * @return 包含所有行的 List
     * @throws SQLException 数据库操作异常
     */
    public static List<Map<String, Object>> toMapList(ResultSet rs) throws SQLException {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 遍历所有行
        while (rs.next()) {
            resultList.add(getRow(rs));
        }
        return resultList;
    }
}
